package com.maosy.demo

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.location.LocationManager
import android.os.Bundle
import android.provider.Settings
import androidx.fragment.app.FragmentActivity
import com.maosy.demo.fragment.WebFragment


class MainActivity : FragmentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    @SuppressLint("MissingPermission")
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (requestCode == WebFragment.LOCATION_REQUEST_CODE) {
            val lm = this.getSystemService(Context.LOCATION_SERVICE) as LocationManager
            val lp = lm.getProviders(true)
            val locationProvider: String
            if (lp.contains(LocationManager.GPS_PROVIDER)) {
                locationProvider = LocationManager.GPS_PROVIDER
            } else if (lp.contains(LocationManager.NETWORK_PROVIDER)) {
                locationProvider = LocationManager.NETWORK_PROVIDER
            } else {
                startActivity(Intent().apply {
                    action = Settings.ACTION_LOCATION_SOURCE_SETTINGS
                })
                return
            }
            if (locationProvider.isNotBlank()) {
                val location = lm.getLastKnownLocation(locationProvider)
                    ?: throw RuntimeException("location 未正确获取")
                MyApp.location = Location(location.latitude, location.longitude)
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }
}



